<?

if (empty($_SERVER['DOCUMENT_ROOT'])) {
	$_SERVER['DOCUMENT_ROOT'] = "/var/www/vhosts/geographs.org/httpdocs/";
} else {
	ini_set("display_errors",1);

}

include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/portals/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');

if (false) {
	init_session();

	if (empty($_SESSION['user_id'])) {
		include($_SERVER['DOCUMENT_ROOT'].'/portals/login.inc.php');
		exit;
	}
}

include($_SERVER['DOCUMENT_ROOT'].'/portals/filter.libs.php');


$id = intval(@$_GET['id']);
if ($id) {
	////
} else {

	//auto!




	$sql = "SELECT p.portal_id,linear_start_id FROM `portal` p 
		INNER JOIN active_cache a USING (portal_id)
		LEFT JOIN cluster c ON (p.portal_id = c.portal_id AND level = 1)
		WHERE p.status_id = 1 AND a.`count` BETWEEN 10 AND 5000 AND (c.portal_id IS NULL OR c.updated < DATE_SUB(NOW(),INTERVAL 1 HOUR) )
		LIMIT 5";

	$portals = getAssoc($sql);

	foreach ($portals as $id => $gid) {
	
		$images = count_active($id);
	
		print "STARTING portal#$id with $images images<BR>\n";
		
		
		$count = 0;
		if ($images > 10 && $images < 5000) {
		
			#########################
			
			$updates = getRow("SELECT gridimage_id,ROUND(AVG(x)) AS cenx,ROUND(AVG(y)) AS ceny,COUNT(*) AS images FROM p2.gridimage{$id}_bi_view GROUP BY '1'");
			
			#########################
			
			$x = $updates['cenx'];
			$y = $updates['ceny'];
			$def = " SQRT((gs.x - $x) * (gs.x - $x) + (gs.y - $y) * (gs.y - $y)) ";
			
			$updates += getRow("SELECT  AVG($def) AS avgdiam, STD($def) AS vardiam,  MAX($def) AS maxdiam FROM p2.gridimage{$id}_bi_view gs GROUP BY '1'");
			
			#########################
			
			$d = 20;
			$left=$x-$d;
			$right=$x+$d-1;
			$top=$y+$d-1;
			$bottom=$y-$d;

			$rectangle = "'POLYGON(($left $bottom,$right $bottom,$right $top,$left $top,$left $bottom))'";
			
			$sql_where = "CONTAINS(GeomFromText($rectangle),point_xy)";
			
			$im = getRow("SELECT gridimage_id FROM p2.gridimage{$id}_bi_view gs WHERE $sql_where ORDER BY ((gs.x - $x) * (gs.x - $x) + (gs.y - $y) * (gs.y - $y)) ASC LIMIT 1");
			
			if (!empty($im) && is_array($im)) {
				$updates += $im;
			}
			
			#########################
						
			$updates['portal_id'] = $id;
			$updates['level'] = 1;
											
			$sql= updates_to_insert('cluster',$updates+array('created'=>'NOW()'));

			$a = updates_to_a($updates);
			$sql .= " ON DUPLICATE KEY UPDATE ".join(',',$a);
			
			queryExecute($sql);
			$count++;
			
			#########################
		}
		
		print "FINISHED $id with $count clusters<BR>\n";
		queryExecute("UPDATE portal SET last_cluster1 = NOW(),updated=updated WHERE portal_id = $id");
	
	}

}

print "<hr>done\n";
